package root.electronclass.electronclass.grade.rota

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.databinding.FragmentClassRoteAddBinding
import root.electronclass.electronclass.databinding.FragmentClassRoteAddItemBinding
import root.electronclass.electronclass.common.base.BasicDialogFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.mvp.rest.ClassApi
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.grade.model.ClassRota
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @author Lokiy
 * @date 2023/2/18 14:58
 */
class ClassAddRotaDialog : BasicDialogFragment<FragmentClassRoteAddBinding>() {

    private var selectColor = ""
    @SuppressLint("NotifyDataSetChanged")
    val adapter = BasicAdapter<String, FragmentClassRoteAddItemBinding> { holder, item ->
        holder.binding.dot.imageTintList = ColorStateList.valueOf(Color.parseColor(item))
        holder.binding.isSelect.isVisible = selectColor == item
        holder.binding.root.setOnClickListener {
            selectColor = item
            notifyDataSetChanged()
        }
    }

    var onSuccess :() -> Unit = {}

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val colorList = arrayListOf(
            "#F24F46",
            "#FF7F17",
            "#FFD000",
            "#1DCF6F",
            "#30BFFF",
            "#306EFF",
            "#6260EB",
            "#F34C88",
            "#C669E8",
            "#B0946C",
            "#7290A6",
            "#CC8B81"
        ).also { selectColor = it[0] }
        binding.recycler.adapter = adapter
        adapter.refresh(colorList)

        onOkClick = click@{
            val item = binding.itemName.text.trim().toString()
            item.ifEmpty { return@click ToastUtil.showToast(requireContext(), "请输入值日项名称") }
            lifecycleScope.launch(CoroutineExceptionHandler()) {
                withContext(Dispatchers.IO) {
                    ClassApi.service.addClassRota(ClassRota(null, item, selectColor))
                }
                ToastUtils.showShort( "添加成功")
                onSuccess.invoke()
                dismiss()
            }
        }

        onCancelClick = {
            dismiss()
        }
    }
}